package com.juzi.wopu.service.impl;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.struts2.ServletActionContext;

import com.juzi.wopu.service.IImageService;

public class IImageServiceImpl implements IImageService{

	static String webapp = ServletActionContext.getServletContext().getRealPath("/");
	
	static String errorImgPath="upload/errorPath.jpg";
	
	@Override
	public String downloadSmallImg(String url) {
		if(url==null){
			return errorImgPath;
		}
		if(!url.startsWith("http://") && !url.startsWith("upload/bigImg/")){//如果不是合法的路径，返回默认的错误图片
			return errorImgPath;
		}
		if(url.startsWith("http://")){
			String s=url.replace("http://", "");
			String[] ss=s.split("/");
			if(ss.length<3){
				return errorImgPath;
			}
			s=s.replace(ss[0]+"/", "");
			s=s.replace(ss[1]+"/", "");
			String tempPath="upload/_temp/"+s;
			s="upload/smallImg/"+s;
			File smallDestFile = new File(webapp, s);
			if(smallDestFile.exists()){
				return s;
			}
			File tempFile = new File(webapp, tempPath);
			
			String dirPath=smallDestFile.getAbsolutePath().replace(smallDestFile.getName(), "");
			File dir=new File(dirPath);
			if(!dir.exists()){
				dir.mkdirs();
			}
			
			String tempDirPath=tempFile.getAbsolutePath().replace(tempFile.getName(), "");
			File tempDir=new File(tempDirPath);
			if(!tempDir.exists()){
				tempDir.mkdirs();
			}
			
			try{
				URL sourceUrl=new URL(url);
				sourceUrl.openConnection().setConnectTimeout(12000);
				sourceUrl.openConnection().setReadTimeout(120000);
				InputStream inputStream=sourceUrl.openStream();
				FileOutputStream outputStream=new FileOutputStream(tempFile);
				
				inputToOutput(inputStream, outputStream);

				//缩略图，高度设置为固定的80像素，宽度按照比例修改
				resizeImage(tempFile, smallDestFile, 100,80, "jpg");
				
				tempFile.delete();
			}catch (Exception e){
				return errorImgPath;
			}
			return s;
		}
		else if(url.startsWith("upload/bigImg/")){
			
			File sourceFile=new File(webapp,url);
			if(!sourceFile.exists()){
				return errorImgPath;
			}
			String smallImgPath="upload/smallImg/"+url.replace("upload/bigImg/", "");
			File smallDestFile = new File(webapp, smallImgPath);
			if(smallDestFile.exists()){
				return smallImgPath;
			}
			String smallDirPath=smallDestFile.getAbsolutePath().replace(smallDestFile.getName(), "");
			File smallDir=new File(smallDirPath);
			if(!smallDir.exists()){
				smallDir.mkdirs();
			}

			try {
				resizeImage(sourceFile, smallDestFile, 80, "jpg");
			} catch (IOException e) {
				return errorImgPath;
			}
			return smallImgPath;
		}
		else {
			return errorImgPath;
		}
	}

	@Override
	public String upload(File file, String typeCode) {
		String desFileName=getUUid()+".jpg";
		String desDir="upload/bigImg/"+typeCode;
		String desFilePath=desDir+"/"+desFileName;
		File dir=new File(webapp,desDir);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File destFile=new File(webapp,desFilePath);
		try {
			FileInputStream fileInputStream=new FileInputStream(file);
			FileOutputStream fileOutputStream=new FileOutputStream(destFile);
			inputToOutput(fileInputStream, fileOutputStream);			
		} catch (IOException e) {
			return "";
		}
		return "http://115.28.85.127:8036/"+desFilePath;
		//return desFilePath;
	}
	
	public void resizeImage(File in, File out, int heightSize, String format) throws IOException {
		FileInputStream is=new FileInputStream(in);
		FileOutputStream os=new FileOutputStream(out);
	    BufferedImage prevImage = ImageIO.read(is);  
	    double width = prevImage.getWidth();  
	    double height = prevImage.getHeight();  
	    double percent = heightSize/height;  
	    int newWidth = (int)(width * percent);  
	    int newHeight = (int)(height * percent);  
	    BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR);  
	    Graphics graphics = image.createGraphics();  
	    graphics.drawImage(prevImage, 0, 0, newWidth, newHeight, null);  
	    ImageIO.write(image, format, os);
	    os.flush();  
	    is.close();  
	    os.close();  
	}
	
	public void resizeImage(File in, File out, int width, int heightSize, String format) throws IOException {
		FileInputStream is=new FileInputStream(in);
		FileOutputStream os=new FileOutputStream(out);
	    BufferedImage prevImage = ImageIO.read(is);  
	    BufferedImage image = new BufferedImage(width, heightSize, BufferedImage.TYPE_INT_BGR);  
	    Graphics graphics = image.createGraphics();  
	    graphics.drawImage(prevImage, 0, 0, width, heightSize, null);  
	    ImageIO.write(image, format, os);
	    os.flush();  
	    is.close();  
	    os.close();  
	}
	
	String getUUid(){
		return UUID.randomUUID().toString();
	}

	public void inputToOutput(InputStream inputStream,OutputStream outputStream) throws IOException{
		int b=inputStream.read();
		while(b!=-1){
			outputStream.write(b);
			b=inputStream.read();
		}
		inputStream.close();
		outputStream.close();
	}

	@Override
	public String upload(File file, String typeCode, int width, int height) {
		String desFileName=getUUid()+".jpg";
		String desDir="upload/bigImg/"+typeCode;
		String desFilePath=desDir+"/"+desFileName;
		File dir=new File(webapp,desDir);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File destFile=new File(webapp,desFilePath);
		try {
			//resizeImage(file, destFile, 645,260, "jpg");
			resizeImage(file, destFile, width,height, "jpg");
			
		} catch (IOException e) {
			return "";
		}
		return "http://115.28.85.127:8036/"+desFilePath;
		//return desFilePath;
	}
}
